package com.lhsy.djcloud.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @author kate
 */
@RestController
@Api(value = "Server-API",tags = "验证码接口")
@Slf4j
public class CaptchaController {


    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private Producer captchaProducer;

    @GetMapping("/login/captcha")
    @ApiOperation(value = "获取验证码")
    public void getKaptchaImage(HttpServletResponse response,@ApiParam("验证码获取标识 每次获取都需要更新") @RequestParam String randomStr) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        String capText = captchaProducer.createText();
        log.info("验证码生成:random:{},cap:{}",randomStr,capText);
        // 将验证码保存到 session 中,
        redisTemplate.opsForValue().set(randomStr, capText,3, TimeUnit.MINUTES);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
